package jp.eisbahn.mgapi.auth;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class AuthorizationUrlBuilder {
    
    public static final String MIXI_AUTHORIZATION_URL = "https://mixi.jp/connect_authorize.pl?";
    public static final String MIXI_AUTHORIZATION_MOBILE_URL = "http://m.mixi.jp/connect_authorize.pl?";
    
    private ClientConfig clientConfig;
    private String[] scopes;
    private String display;
    private Device device;
    
    public AuthorizationUrlBuilder() {
        super();
        device = Device.PC;
    }

    public AuthorizationUrlBuilder setClientConfig(ClientConfig config) {
        this.clientConfig = config;
        return this;
    }

    public ClientConfig getClientConfig() {
        return clientConfig;
    }

    public AuthorizationUrlBuilder setScopes(String[] scopes) {
        this.scopes = scopes;
        return this;
    }

    public String[] getScopes() {
        return scopes;
    }

    public AuthorizationUrlBuilder setDisplay(String display) {
        this.display = display;
        return this;
    }

    public String getDisplay() {
        return display;
    }

    public AuthorizationUrlBuilder setDevice(Device device) {
        this.device = device;
        return this;
    }

    public Device getDevice() {
        return device;
    }

    public String build() {
        try {
            StringBuilder sb = new StringBuilder();
            if (device.equals(Device.MOBILE)) {
                sb.append(MIXI_AUTHORIZATION_MOBILE_URL);
            } else {
                sb.append(MIXI_AUTHORIZATION_URL);
            }
            sb.append("client_id=");
            sb.append(URLEncoder.encode(clientConfig.getClientId(), "UTF-8"));
            sb.append("&response_type=code&scope=");
            sb.append(URLEncoder.encode(joinScopes(), "UTF-8"));
            if (device != Device.MOBILE) {
                sb.append("&display=");
                sb.append(display);
            }
            return sb.toString();
        } catch(UnsupportedEncodingException e) {
            throw new IllegalArgumentException(e);
        }
    }
    
    private String joinScopes() {
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        for (int i = 0; i < scopes.length; i++) {
            if (!first) {
                sb.append(" ");
            } else {
                first = false;
            }
            sb.append(scopes[i]);
        }
        return sb.toString();
    }

}
